<?php
/**
 * File containing the BRail_Ldap_Security class.
 * @package BRail_Ldap
 */

/**
 * @package BRail_Ldap
 */
class BRail_Ldap_Security
{
    /**
     * @var BRail_Ldap_Adapter $_ldapAdapter
     */
    private $_ldapAdapter = null;

    /**
     * @param BRail_Ldap_Adapter $ldapAdapter
     */
    public function __construct(BRail_Ldap_Adapter $ldapAdapter)
    {
        $this->_ldapAdapter = $ldapAdapter;
    }

    /**
     * @param string $login
     * @param string $group
     * @param boolean $recursive
     * @return boolean
     */
    public function isUserInGroup($login, $group, $recursive = false)
    {
        $userQueryTool = new BRail_Ldap_UserQueryTool($this->_ldapAdapter);
        $users = $userQueryTool->searchByLogin($login);
        $userGroups = $users[0]->groups;
        return $this->groupMatch($userGroups, $group, $recursive);
    }

    /**
     * @param array $userGroups
     * @param string $group
     * @param boolean $recursive
     * @return boolean
     */
    public function groupMatch($userGroups, $group, $recursive = false)
    {
        if ($recursive === false) {
            return in_array($group, $userGroups);
        }
        $groupQueryTool = new BRail_Ldap_GroupQueryTool($this->_ldapAdapter);
        return (boolean) count(array_intersect(
            $userGroups,
            $groupQueryTool->getNested($group)
        ));
    }
}
